package com.onenine.app.utils;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Pair;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.onenine.app.R;
import com.onenine.base.utils.AppConfig;
import com.onenine.common.util.ApUtils;
import com.onenine.common.util.ScreenUtils;
import com.onenine.common.util.SizeUtils;
import com.onenine.glide.GlideApp;
import com.onenine.glide.internal.FastBlur;
import com.onenine.glide.transform.BlurTransformation;
import com.othershe.combinebitmap.CombineBitmap;
import com.othershe.combinebitmap.layout.WechatLayoutManager;
import com.othershe.combinebitmap.listener.OnProgressListener;


/**
 * 创建时间：2018/6/11 0011 17:45
 * 创建人：fly
 * 功能描述：Glide帮助类
 */
public class GlideUtils {

    public static final int DEFAULT_ROUND_CORNER = SizeUtils.dp2px(10);
    public static final float DENSITY = ScreenUtils.getScreenDensity();
    public static final float IMAGE_WIDTH_60 = 60 * DENSITY;
    public static final float IMAGE_HEIGHT_60 = 60 * DENSITY;
    public static final float IMAGE_WIDTH_150 = 150 * DENSITY;
    public static final float IMAGE_HEIGHT_150 = 150 * DENSITY;
    public static final float IMAGE_WIDTH_180 = 180 * DENSITY;
    public static final float IMAGE_HEIGHT_180 = 180 * DENSITY;
    public static final float IMAGE_WIDTH_240 = 240 * DENSITY;
    public static final float IMAGE_HEIGHT_240 = 240 * DENSITY;

    /**
     * 自适应大小回调
     */
    public interface OnFitCallback {
        void callback(Pair<Float, Float> sizePair);
    }

    /**
     * 加载图片
     *
     * @param context
     * @param imageView
     * @param avatar
     */
    public static void loadSrcImage(Context context, ImageView imageView, String avatar) {
        GlideApp.with(context).load(avatar)
                .error(R.drawable.shape_image_placeholder_bg)
                .transform(new CenterCrop())
                .into(imageView);
    }

    /**
     * 加载圆角头像
     *
     * @param context
     * @param imageView
     * @param avatar
     */
    public static void loadRoundImage(Context context, ImageView imageView, String avatar) {
        GlideApp.with(context).load(avatar)
                .transform(new MultiTransformation<>(new CenterCrop(), new RoundedCorners(DEFAULT_ROUND_CORNER)))
                .into(imageView);
    }

    /**
     * 加载圆角头像
     *
     * @param activity
     * @param imageView
     * @param avatar
     */
    public static void loadRoundImage(Activity activity, ImageView imageView, String avatar, int roundingRadius) {
        GlideApp.with(activity).load(avatar)
                .transform(new MultiTransformation<>(new CenterCrop(), new RoundedCorners(roundingRadius)))
                .into(imageView);
    }

    /**
     * 加载圆角图片
     *
     * @param context
     * @param imageView
     * @param defaultDrawable
     * @param avatar
     * @param roundingRadius
     */
    public static void loadRoundImage(Context context, ImageView imageView, Drawable defaultDrawable, String avatar, int roundingRadius) {
        GlideApp.with(context).load(avatar)
                .placeholder(defaultDrawable)
                .transform(new MultiTransformation<>(new CenterCrop(), new RoundedCorners(roundingRadius)))
                .into(imageView);
    }

    /**
     * 加载圆角图片
     *
     * @param context
     * @param imageView
     * @param avatar
     */
    public static void loadRoundImage(Context context, ImageView imageView, String avatar, int roundingRadius) {
        GlideApp.with(context).load(avatar)
                .transform(new MultiTransformation<>(new CenterCrop(), new RoundedCorners(roundingRadius)))
                .into(imageView);
    }

    /**
     * 加载圆形头像
     *
     * @param context
     * @param imageView
     * @param avatar
     */
    public static void loadCircleAvatar(Context context, ImageView imageView, String avatar) {
        GlideApp.with(context).load(avatar)
                .transform(new CircleCrop()).into(imageView);
    }

    /**
     * 加载圆形头像
     *
     * @param activity
     * @param imageView
     * @param avatar
     */
    public static void loadCircleAvatar(Activity activity, ImageView imageView, String avatar) {
        GlideApp.with(activity).load(avatar)
                .transform(new CircleCrop()).into(imageView);
    }

    /**
     * 加载圆角头像
     *
     * @param fragment
     * @param imageView
     * @param avatar
     */
    public static void loadRoundImage(Fragment fragment, ImageView imageView, String avatar, int roundingRadius) {
        GlideApp.with(fragment).load(avatar)
                .transform(new MultiTransformation<>(new CenterCrop(), new RoundedCorners(roundingRadius)))
                .into(imageView);
    }

    /**
     * 加载圆角头像
     *
     * @param fragment
     * @param imageView
     * @param avatar
     */
    public static void loadRoundImage(android.support.v4.app.Fragment fragment, ImageView imageView, String avatar, int roundingRadius) {
        GlideApp.with(fragment).load(avatar)
                .transform(new MultiTransformation<>(new CenterCrop(), new RoundedCorners(roundingRadius)))
                .into(imageView);
    }

    /**
     * 加载圆角头像
     *
     * @param fragment
     * @param imageView
     * @param avatar
     */
    public static void loadRoundImage(Fragment fragment, ImageView imageView, String avatar, int roundingRadius, int width, int height) {
        GlideApp.with(fragment).load(avatar)
                .transform(new MultiTransformation<>(new CenterCrop(), new RoundedCorners(roundingRadius)))
                .override(width, height)
                .into(imageView);
    }

    /**
     * 加载圆角头像
     *
     * @param fragment
     * @param imageView
     * @param avatar
     */
    public static void loadRoundImage(android.support.v4.app.Fragment fragment, ImageView imageView, String avatar, int roundingRadius, int width, int height) {
        GlideApp.with(fragment).load(avatar)
                .transform(new MultiTransformation<>(new CenterCrop(), new RoundedCorners(roundingRadius)))
                .override(width, height)
                .into(imageView);
    }

    /**
     * 加载圆角头像
     *
     * @param fragment
     * @param imageView
     * @param avatar
     */
    public static void loadRoundBlurImage(android.support.v4.app.Fragment fragment, ImageView imageView, String avatar, int roundingRadius, int width, int height) {
        GlideApp.with(fragment).load(avatar)
                .transform(new MultiTransformation<>(new CenterCrop()
                        , new RoundedCorners(roundingRadius), new BlurTransformation()))
                .override(width, height)
                .into(imageView);
    }

    /**
     * 加载圆形头像
     *
     * @param fragment
     * @param imageView
     * @param avatar
     */
    public static void loadCircleAvatar(Fragment fragment, ImageView imageView, String avatar) {
        GlideApp.with(fragment).load(avatar)
                .transform(new CircleCrop()).into(imageView);
    }

    /**
     * 加载圆形头像
     *
     * @param view
     * @param imageView
     * @param avatar
     */
    public static void loadCircleAvatar(View view, ImageView imageView, String avatar) {
        GlideApp.with(view).load(avatar)
                .transform(new CircleCrop()).into(imageView);
    }

    /**
     * 加载圆形头像
     *
     * @param context
     * @param imageView
     * @param avatar
     */
    public static void loadCircleAvatar(Context context, ImageView imageView, Drawable defaultDrawable, String avatar) {
        GlideApp.with(context).load(avatar)
                .transform(new CircleCrop()).into(imageView);
    }


    /**
     * 加载圆形头像
     *
     * @param fragment
     * @param imageView
     * @param avatar
     */
    public static void loadCircleAvatar(android.support.v4.app.Fragment fragment, ImageView imageView, String avatar) {
        GlideApp.with(fragment).load(avatar)
                .transform(new CircleCrop()).into(imageView);
    }

    /**
     * 加载自适应单图
     * 默认圆角,宽高限制
     *
     * @param context
     * @param imageView
     * @param imageUrl
     */
    public static void loadSquareImageFitWidth(Context context, final ImageView imageView, final String imageUrl, int maxWidth) {
        GlideApp.with(context).load(imageUrl)
                .transform(new MultiTransformation<>(new CenterCrop(), new RoundedCorners(DEFAULT_ROUND_CORNER)))
                .into(new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                        if (imageView.getScaleType() != ImageView.ScaleType.FIT_XY) {
                            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                        }
                        ViewGroup.LayoutParams params = imageView.getLayoutParams();
                        Pair<Float, Float> fitSize = getFitImageSize(resource.getIntrinsicWidth(), resource.getIntrinsicHeight(), maxWidth);
                        params.width = fitSize.first.intValue();
                        params.height = fitSize.second.intValue();
                        imageView.setImageDrawable(resource);
                    }
                });
    }

    /**
     * 加载自适应单图
     * 默认圆角,宽高限制
     *
     * @param context
     * @param imageView
     * @param imageUrl
     */
    public static void loadRoundImageFitWidth(Context context, ImageView imageView, String imageUrl, int maxWidth) {
        loadRoundImageFitWidth(context, imageView, imageUrl, DEFAULT_ROUND_CORNER, maxWidth);
    }

    /**
     * 加载自适应视频封面
     *
     * @param context
     * @param imageView
     * @param imageUrl
     * @param maxWidth
     * @param callback
     */
    public static void loadVideoImageFitWidth(Context context, ImageView imageView, String imageUrl, int maxWidth, OnFitCallback callback) {
        GlideApp.with(context).load(imageUrl)
                .transform(new MultiTransformation<>(new CenterCrop()))
                .into(new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                        if (imageView.getScaleType() != ImageView.ScaleType.FIT_XY) {
                            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                        }
                        ViewGroup.LayoutParams params = imageView.getLayoutParams();
                        Pair<Float, Float> fitSize = getFitVideoSize(resource.getIntrinsicWidth(), resource.getIntrinsicHeight(), maxWidth);
                        params.width = fitSize.first.intValue();
                        params.height = fitSize.second.intValue();
                        imageView.setImageDrawable(resource);
                        if (callback != null) {
                            callback.callback(fitSize);
                        }
                    }
                });
    }

    /**
     * 加载自适应最大可全屏大小
     *
     * @param context
     * @param imageView
     * @param imageUrl
     */
    public static void loadFullSquareImageFitWidth(Context context, final ImageView imageView, String imageUrl) {
        GlideApp.with(context).load(imageUrl)
                .transform(new MultiTransformation<>(new CenterCrop()))
                .into(new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                        if (imageView.getScaleType() != ImageView.ScaleType.FIT_XY) {
                            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                        }
                        ViewGroup.LayoutParams params = imageView.getLayoutParams();
                        Pair<Float, Float> fitSize = getFullScreenFitImageSize(resource.getIntrinsicWidth(), resource.getIntrinsicHeight());
                        params.width = fitSize.first.intValue();
                        params.height = fitSize.second.intValue();
                        imageView.setImageDrawable(resource);
                    }
                });
    }

    /**
     * 加载自适应最大可全屏大小
     *
     * @param context
     * @param imageView
     * @param imageUrl
     */
    public static void loadFullImageFitWidth(Context context, final ImageView imageView, String imageUrl) {
        GlideApp.with(context).load(imageUrl)
                .transform(new MultiTransformation<>(new CenterCrop(), new RoundedCorners(DEFAULT_ROUND_CORNER)))
                .into(new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                        if (imageView.getScaleType() != ImageView.ScaleType.FIT_XY) {
                            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                        }
                        ViewGroup.LayoutParams params = imageView.getLayoutParams();
                        Pair<Float, Float> fitSize = getFullScreenFitImageSize(resource.getIntrinsicWidth(), resource.getIntrinsicHeight());
                        params.width = fitSize.first.intValue();
                        params.height = fitSize.second.intValue();
                        imageView.setImageDrawable(resource);
                    }
                });
    }

    /**
     * 加载自适应单图
     *
     * @param context
     * @param imageView
     * @param imageUrl
     * @param roundingRadius
     */
    public static void loadRoundImageFitWidth(Context context, final ImageView imageView, String imageUrl, int roundingRadius, int maxWidth) {
        GlideApp.with(context).load(imageUrl)
                .transform(new MultiTransformation<>(new CenterCrop(), new RoundedCorners(roundingRadius)))
                .into(new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                        if (imageView.getScaleType() != ImageView.ScaleType.FIT_XY) {
                            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                        }
                        ViewGroup.LayoutParams params = imageView.getLayoutParams();
                        Pair<Float, Float> fitSize = getFitImageSize(resource.getIntrinsicWidth(), resource.getIntrinsicHeight(), maxWidth);
                        params.width = fitSize.first.intValue();
                        params.height = fitSize.second.intValue();
                        imageView.setImageDrawable(resource);
                    }
                });
    }

    /**
     * 加载自适应单图
     * 默认圆角
     *
     * @param fragment
     * @param imageView
     * @param imageUrl
     */
    public static void loadRoundImageFitWidth(android.support.v4.app.Fragment fragment, ImageView imageView, String imageUrl, int maxWidth) {
        loadRoundImageFitWidth(fragment, imageView, imageUrl, DEFAULT_ROUND_CORNER, maxWidth);
    }

    /**
     * 加载自适应单图
     *
     * @param fragment
     * @param imageView
     * @param imageUrl
     * @param roundingRadius
     */
    public static void loadRoundImageFitWidth(android.support.v4.app.Fragment fragment, final ImageView imageView
            , final String imageUrl, final int roundingRadius, final int maxWidth) {
        GlideApp.with(fragment).load(imageUrl)
                .transform(new MultiTransformation<>(new CenterCrop(), new RoundedCorners(roundingRadius)))
                .into(new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                        if (imageView.getScaleType() != ImageView.ScaleType.FIT_XY) {
                            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                        }
                        ViewGroup.LayoutParams params = imageView.getLayoutParams();
                        Pair<Float, Float> fitSize = getFitImageSize(resource.getIntrinsicWidth(), resource.getIntrinsicHeight(), maxWidth);
                        params.width = fitSize.first.intValue();
                        params.height = fitSize.second.intValue();
                        imageView.setImageDrawable(resource);
                    }
                });
    }

    /**
     * 图片异步加载圆形图片
     *
     * @param context
     * @param imageUrl
     * @param target
     */
    public static void loadSyncCircleImage(Context context, String imageUrl, SimpleTarget target) {
        GlideApp.with(context).load(imageUrl)
                .transform(new CenterCrop())
                .into(target);
    }

    /**
     * 加载自适应单图,大小适中
     * 用于聊天图片消息显示
     *
     * @param imageView
     * @param imageUrl
     * @param isBlur
     */
    public static void loadChatFitImage(final ImageView imageView, final String imageUrl, final boolean isBlur) {
        Glide.with(ApUtils.getApp())
                .asBitmap()
                .load(imageUrl)
                .apply(new RequestOptions().fitCenter())
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        int imageWidth = resource.getWidth();
                        int imageHeight = resource.getHeight();
                        float width, height;
                        if (imageWidth > imageHeight) {
                            if (imageWidth > IMAGE_WIDTH_180) {
                                float temp = IMAGE_WIDTH_180 / imageWidth * imageHeight;
                                height = temp > IMAGE_HEIGHT_150 ? temp : IMAGE_HEIGHT_150;
                                width = IMAGE_WIDTH_180;
                            } else if (imageWidth < IMAGE_WIDTH_150) {
                                float temp = IMAGE_WIDTH_150 / imageWidth * imageHeight;
                                height = temp < IMAGE_HEIGHT_180 ? temp : IMAGE_HEIGHT_180;
                                width = IMAGE_WIDTH_150;
                            } else {
                                width = (IMAGE_WIDTH_180 + IMAGE_WIDTH_150) / 2;
                                height = imageHeight / (imageWidth / width);
                            }
                        } else {
                            if (imageHeight > IMAGE_HEIGHT_180) {
                                float temp = IMAGE_HEIGHT_180 / imageHeight * imageWidth;
                                width = temp > IMAGE_WIDTH_150 ? temp : IMAGE_WIDTH_150;
                                height = IMAGE_HEIGHT_180;
                            } else if (imageHeight < IMAGE_HEIGHT_150) {
                                float temp = IMAGE_HEIGHT_150 / imageHeight * imageWidth;
                                width = temp < IMAGE_WIDTH_180 ? temp : IMAGE_WIDTH_180;
                                height = IMAGE_HEIGHT_150;
                            } else {
                                height = (IMAGE_HEIGHT_180 + IMAGE_HEIGHT_150) / 2;
                                width = imageWidth / (imageHeight / height);
                            }
                        }
                        ViewGroup.LayoutParams params = imageView.getLayoutParams();
                        params.width = (int) width;
                        params.height = (int) height;
                        imageView.setLayoutParams(params);
                        Matrix matrix = new Matrix();
                        float scaleWidth = width / imageWidth;
                        float scaleHeight = height / imageHeight;
                        matrix.postScale(scaleWidth, scaleHeight);
                        Bitmap bitmap = Bitmap.createBitmap(resource, 0, 0, imageWidth, imageHeight, matrix, true);
                        if (isBlur) {
                            imageView.setImageBitmap(FastBlur.blur(bitmap, 10, false));
                        } else {
                            imageView.setImageBitmap(bitmap);
                        }
                    }
                });
    }

    /**
     * 生成最大全屏大小的图片大小
     *
     * @param imageWidth
     * @param imageHeight
     * @return
     */
    public static Pair<Float, Float> getFullScreenFitImageSize(float imageWidth, float imageHeight) {
        Pair<Float, Float> result;
        if (imageWidth > imageHeight) {
            if (imageWidth > AppConfig.SCREEN_WIDTH) {
                float temp = AppConfig.SCREEN_WIDTH / imageWidth * imageHeight;
                result = Pair.create((float) AppConfig.SCREEN_WIDTH, temp > IMAGE_HEIGHT_60 ? temp : IMAGE_HEIGHT_60);
            } else if (imageWidth < IMAGE_WIDTH_60) {
                float temp = IMAGE_WIDTH_60 / imageWidth * imageHeight;
                result = Pair.create(IMAGE_WIDTH_60, temp < AppConfig.SCREEN_HEIGHT ? temp : AppConfig.SCREEN_HEIGHT);
            } else {
                result = Pair.create(imageWidth, imageHeight);
            }
        } else {
            if (imageHeight > AppConfig.SCREEN_HEIGHT) {
                float temp = AppConfig.SCREEN_HEIGHT / imageHeight * imageWidth;
                result = Pair.create(temp > IMAGE_WIDTH_60 ? temp : IMAGE_WIDTH_60, (float) AppConfig.SCREEN_HEIGHT);
            } else if (imageHeight < IMAGE_HEIGHT_60) {
                float temp = IMAGE_HEIGHT_60 / imageHeight * imageWidth;
                result = Pair.create(temp < AppConfig.SCREEN_WIDTH ? temp : AppConfig.SCREEN_WIDTH, IMAGE_HEIGHT_60);
            } else {
                result = Pair.create(imageWidth, imageHeight);
            }
        }
        return result;
    }

    /**
     * 获取自适应图片合理大小
     *
     * @param imageWidth
     * @param imageHeight
     * @return
     */
    public static Pair<Float, Float> getFitVideoSize(float imageWidth, float imageHeight, int maxWidth) {
        Pair<Float, Float> result;
        if (imageWidth > imageHeight) {
            result = Pair.create((float) maxWidth, maxWidth * imageHeight / imageWidth);
        } else {
            if (imageHeight > IMAGE_HEIGHT_240) {
                float temp = IMAGE_HEIGHT_240 / imageHeight * imageWidth;
                result = Pair.create(temp > IMAGE_WIDTH_60 ? temp : IMAGE_WIDTH_60, IMAGE_HEIGHT_240);
            } else if (imageHeight < IMAGE_HEIGHT_60) {
                float temp = IMAGE_HEIGHT_60 / imageHeight * imageWidth;
                result = Pair.create(temp < IMAGE_WIDTH_240 ? temp : IMAGE_WIDTH_240, IMAGE_HEIGHT_60);
            } else {
                result = Pair.create(imageWidth, imageHeight);
            }
        }
        return result;
    }

    /**
     * 获取自适应图片合理大小
     *
     * @param imageWidth
     * @param imageHeight
     * @return
     */
    public static Pair<Float, Float> getFitImageSize(float imageWidth, float imageHeight, int maxWidth) {
        Pair<Float, Float> result;
        if (imageWidth > imageHeight) {
            result = Pair.create((float) maxWidth, maxWidth * imageHeight / imageWidth);
        } else {
            if (imageHeight > IMAGE_HEIGHT_240) {
                float temp = IMAGE_HEIGHT_240 / imageHeight * imageWidth;
                result = Pair.create(temp > IMAGE_WIDTH_60 ? temp : IMAGE_WIDTH_60, IMAGE_HEIGHT_240);
            } else if (imageHeight < IMAGE_HEIGHT_60) {
                float temp = IMAGE_HEIGHT_60 / imageHeight * imageWidth;
                result = Pair.create(temp < IMAGE_WIDTH_240 ? temp : IMAGE_WIDTH_240, IMAGE_HEIGHT_60);
            } else {
                result = Pair.create(imageWidth, imageHeight);
            }
        }
        return result;
    }

    /**
     * 生成微信群头像
     *
     * @param context
     * @param imageView
     * @param urls
     */
    public static void loadWechatBitmap(Context context, ImageView imageView, OnProgressListener progressListener, String... urls) {
        CombineBitmap.init(context)
                .setLayoutManager(new WechatLayoutManager())
                .setSize(180)
                .setGap(3)
                .setGapColor(Color.parseColor("#E8E8E8"))
                .setUrls(urls)
                .setPlaceholder(R.mipmap.ic_default_avatar_round)
                .setImageView(imageView)
                .setOnProgressListener(progressListener)
                .build();
    }

}
